local lsp = require("lspconfig")
local shared = require("plugins.lsp")
local clangd_ext = require("clangd_extensions")

local clangd_path = vim.fn.exepath("clangd") or "/usr/bin/clangd"

-- 基础 clangd 配置
lsp.clangd.setup({
  on_attach = function(client, bufnr)
    shared.on_attach(client, bufnr)
    -- C/C++ 专用键位
    local opts = { noremap = true, silent = true, buffer = bufnr }
    vim.keymap.set("n", "<leader>ch", "<cmd>ClangdSwitchSourceHeader<CR>", opts)
  end,
  -- ===============================================
  -- 添加这一段是因为我使用的事平板电脑模拟的Linux系统，无法和真正的系统相比较造成的
  capabilities = require("cmp_nvim_lsp").default_capabilities(),
  --capabilities = shared.capabilities,
  filetypes = { "c", "cpp", "objc", "objcpp" },
  -- =======================================
  cmd = {
    clangd_path,
    "--background-index",
    "--clang-tidy",
    "--header-insertion=iwyu",
    "--completion-style=detailed",
    "--function-arg-placeholders",
    "--fallback-style=llvm"
  },
  mason = false,
})

-- clangd 扩展配置
clangd_ext.setup({
  server = {
    capabilities = shared.capabilities,
    cmd = {
      clangd_path,
      "--background-index",
      "--clang-tidy",
      "--header-insertion=never"
    }
  },
  extensions = {
    autoSetHints = true,
    hover_with_actions = true,
    inlay_hints = {
      only_current_line = false,
      show_parameter_hints = true,
      parameter_hints_prefix = " ← ",
      other_hints_prefix = " → ",
    }
  }
})

-- 自动检测编译数据库
vim.api.nvim_create_autocmd("FileType", {
  pattern = { "c", "cpp" },
  callback = function()
    local compile_commands = vim.fn.findfile("compile_commands.json", ".;")
    if compile_commands ~= "" then
      lsp.clangd.setup({
        root_dir = vim.fs.dirname(compile_commands)
      })
    end
  end
})
